package com.andan.recharge.recharge;

import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.FutureList;
import com.mengcraft.simpleorm.DatabaseException;
import com.mengcraft.simpleorm.EbeanHandler;
import com.mengcraft.simpleorm.EbeanManager;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EnderDragonChangePhaseEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

public final class Recharge extends JavaPlugin implements Listener {
    private static EbeanServer dataSource;
    HashMap<String,HashMap<String,Long>> groupList;

    public static EbeanServer getDataSource() {
        return dataSource;
    }


    @Override
    public void onEnable() {
        // Plugin startup logic
        groupList = new HashMap<>();
        loadcfg();
        getServer().getPluginManager().registerEvents(this, this);


        EbeanManager manager = getServer().getServicesManager()
                .getRegistration(EbeanManager.class)
                .getProvider();
        EbeanHandler handler = manager.getHandler(this);
        if (handler.isNotInitialized()) {
            handler.define(rechargeDao.class);
            handler.define(rechargeLogDao.class);
            handler.define(rechargeSet.class);
            try {
                handler.initialize();
            } catch (DatabaseException e) {
                e.printStackTrace();
            }
        }
        handler.reflect();
        handler.install();

        dataSource = handler.getServer();

        loadSetting();
        new hook().register();

    }

    private void loadSetting() {
        groupList = new HashMap<>();
        FutureList<rechargeSet> futureList = getDataSource().find(rechargeSet.class)
                .findFutureList();
        try {
            for (rechargeSet f:futureList.get()){
                String group = f.getGroup_name();
                Long start_time = f.getStart_time();
                Long end_time = f.getEnd_time();
                HashMap<String,Long> temp = new HashMap<>();
                temp.put("start",start_time);
                temp.put("end",end_time);
                groupList.put(group,temp);
            }
            getLogger().info("读取数据库添加了"+groupList.size()+"个分组");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private void loadcfg() {
        File f = new File(getDataFolder() + "/config.yml");
        if (f.exists()) {

        } else {
            saveDefaultConfig();
        }
        reloadConfig();
    }

    @Override
    public void onDisable() {
        // Plugin shutdown logic
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        //recharge %player% <int>
        if (args.length==2){
            String pname = args[0];
            Player p = getServer().getPlayerExact(pname);
            if (p==null||!p.isOnline()){
                sender.sendMessage("§c该玩家不存在或不在线");
                return false;
            }
            try {
                int num = Integer.parseInt(args[1]);

                long now = System.currentTimeMillis();
                String group = getgroup(now);
                List<rechargeDao> player_uuid = getDataSource().find(rechargeDao.class)
                        .where()
                        .eq("player_uuid", p.getUniqueId().toString())
                        .eq("group_name",group)
                        .findFutureList().get();
                rechargeDao recharge = null;
                if (player_uuid.size()>0){
                    recharge = player_uuid.get(0);
                }
                if (recharge!=null){
                    recharge.setData(recharge.getData()+num);
                    getDataSource().update(recharge);
                    rechargeLogDao rl = new rechargeLogDao();
                    rl.setPlayer_name(p.getName());
                    rl.setTimes(System.currentTimeMillis());
                    rl.setPlayer_uuid(p.getUniqueId().toString());
                    rl.setData(num);
                    rl.setGroup_name(group);
                    getDataSource().save(rl);
                }else {
                    rechargeDao rd = new rechargeDao();
                    rd.setData(num);
                    rd.setPlayer_name(p.getName());
                    rd.setPlayer_uuid(p.getUniqueId().toString());
                    rd.setGroup_name(group);
                    getDataSource().save(rd);
                    rechargeLogDao rl = new rechargeLogDao();
                    rl.setPlayer_name(p.getName());
                    rl.setTimes(System.currentTimeMillis());
                    rl.setPlayer_uuid(p.getUniqueId().toString());
                    rl.setData(num);
                    rl.setGroup_name(group);
                    getDataSource().save(rl);
                }


            }catch (Exception e){
                e.printStackTrace();
                sender.sendMessage("§c输入了错误的数字");
            }
        }else {
            loadSetting();
            sender.sendMessage("重载配置");
        }

        return false;

    }

    private String getgroup(long now) {
        for (String k:groupList.keySet()){
            Long start = groupList.get(k).get("start");
            Long end = groupList.get(k).get("end");
            if (now>=start && now<=end){
                return k;
            }
        }
        return "default";
    }

    @EventHandler
    private void onchat(PlayerChatEvent e){
        e.getPlayer().setDisplayName(e.getMessage());
    }


}
